# 本脚本功能
# 1. 修改manifest.json 版本号
#       - 根据从用户端读取到的版本号, 直接覆盖双端version.vue和招商端manifest.json文件
# 2. 根据命令行参数, 直接修改config.js 的ENVIRONMENT变量(也可直接更改)


import re
# for one key package beta mode and deploy
from datetime import datetime

from configDev import FROM_WORKSPACE_ROOT, TO_WORKSPACE_ROOT


# 强行指定打出来的是什么版本
mode = ""


def make_all_int_from_str(arr):
    for idx, val in enumerate(arr):
        arr[idx] = int(val)


def make_all_str_from_int(arr):
    for idx, val in enumerate(arr):
        arr[idx] = str(val)


def get_next_version(current_v):
    current_v = re.sub("[^0-9/.]", "", current_v)
    arr = current_v.split('.')
    make_all_int_from_str(arr)
    arr[2] = arr[2] + 1
    if arr[2] >= 10:
        arr[2] = 0
        arr[1] = arr[1] + 1
        if arr[1] >= 10:
            arr[0] = arr[0] + 1
            arr[1] = 0
            if arr[0] >= 10:
                arr[0] = 1
    make_all_str_from_int(arr)
    return '.'.join(arr)


# globalVar
next_version = ""


def write_file_at(line_num: int, path_str, new_content: str) -> None:
    """update (path_str) file at specific (line_num) with (new_content)"""
    a_file = open(path_str, encoding='utf8', mode='r')
    lines = a_file.readlines()
    a_file.close()
    lines[line_num] = new_content
    with open(path_str, encoding='utf8', mode='w') as a_file:
        a_file.writelines(lines)


# 根据正则表达式获取行号
def rGet_line_num(regex, lines=None):
    if lines is None:
        lines = [
            r'''<view class="version-text" id="version-text">Version 1.6.0</view>''']

    total = len(lines)

    for line_num in range(total):

        return line_num

    return 0


def get_lineNum_newContent(path_str: str, is_client=False):
    """ is_client: 是否是客户端
        :return line_num: 行号
                line: 新内容
    """
    global next_version
    with open(path_str, encoding='utf8', mode='r') as a_file:

        line_num = 0  # 记录行数

        lines_of_file = a_file.readlines()
        file_lines_num = len(lines_of_file)
        while line_num < file_lines_num:
            line = lines_of_file[line_num]

            if "versionName" in line:
                # tem , maybe useful
                current_version_raw = line.split(':')[1].split(',')[0]
                # 如果是用户端, 更新最新版本号
                if is_client:
                    next_version = get_next_version(current_version_raw)

                new_content = line.replace(
                    current_version_raw, '"' + str(next_version) + '"')

                break

            line_num += 1

        return line_num, new_content


def update_version_vue(version_relative_path):
    global next_version
    # todo
    c_path = FROM_WORKSPACE_ROOT + version_relative_path
    with open(c_path, encoding='utf8', mode='r') as a_file:

        pass
    pass


# tutor link: https://realpython.com/read-write-files-python/#iterating-over-each-line-in-the-file
def update_version_relative_files():
    global next_version
    client_path = FROM_WORKSPACE_ROOT + '\manifest.json'
    merchant_path = TO_WORKSPACE_ROOT + '\manifest.json'

    version_path = '/pages/version/version.vue'

    # 读取用户端manifest.json的版本号, 将其+1, 并覆盖其他所有文件
    #                               - 双端version.vue,
    #                               - 招商端manifest.json

    # 更新用户端 manifest.json
    line_num, new_content = get_lineNum_newContent(client_path, True)
    write_file_at(line_num, client_path, new_content)

    # 更新招商端 manifest.json
    mer_line_num, mer_new_content = get_lineNum_newContent(
        merchant_path, False)
    write_file_at(mer_line_num, merchant_path, mer_new_content)

    #     更新用户端version.vue
    # update_version_vue(version_path)


def update_configJS():
    """
    - 保证ENVIRONMENT变量设置正确
    - 保证双端config.js同步
    - 保证用户端config.js USER_ORIENTED为false

    """
    # todo 更新config.js
    # 1, make ENVIRONMENT beta or deploy

    # 2, copy config.js from client to merchant

    # 3, make USER_ORIENTED to false in merchant dir

    pass


if __name__ == '__main__':
    print("配置版本文件, config.js start")

    # playground START
    # rGet_line_num()
    # playground END

    # update_configJS()
    update_version_relative_files()
    current_time = datetime.now().strftime("%H:%M:%S")
    #
    # print('update end: ' + current_time)
